import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:english_words/english_words.dart';

class ScrollbarWidget extends StatefulWidget {
  const ScrollbarWidget({required Key key});

  @override
  _ScrollbarWidgetState createState() => new _ScrollbarWidgetState();
}

class _ScrollbarWidgetState extends State<ScrollbarWidget> {
  @override
  void initState() {
    super.initState();
    //初始化状态
    print("initState");
  }

  // 头像
  dynamic avatar = Image.network(
    "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4",
    width: 100.0,
    color: Colors.blue,
    colorBlendMode: BlendMode.difference,
  );

  List<Widget> listWidglet(String text) {
    List<Widget> list = <Widget>[];
    for (int i = 0; i < 100; i++) {
      list.add(Text(text + i.toString()));
      print("listview 创建 $i");
    }

    return list;
  }

  ///无限加载数据
  void startListview() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return InfiniteListView();
    }));
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    return Scaffold(
        body: SingleChildScrollView(
      child: Column(
        children: [
          TextButton(
            child: Text("跳转至自定义的StatelessWidget界面echo"),
            style: ButtonStyle(),
            onPressed: startListview,
          ),
          SizedBox(
            height: 200,
            child: ListView(
              shrinkWrap: true,
              padding: const EdgeInsets.all(20.0),
              children: listWidglet("数组文本集合"),
            ),
          ),
          _ListViewBuilder2(),

          //可以在生成的列表项之间添加一个分割组件，类似下划线，它比ListView.builder多了一个separatorBuilder参数，该参数是一个分割组件生成器。
          ListViewSeparated3(),
        ],
      ),
    ));
  }

  @override
  void didUpdateWidget(covariant ScrollbarWidget oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void deactivate() {
    super.deactivate();
    print("deactive");
  }

  @override
  void dispose() {
    super.dispose();
    print("dispose");
  }

  @override
  void reassemble() {
    super.reassemble();
    print("reassemble");
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("didChangeDependencies");
  }
}

class _ListViewBuilder2 extends StatelessWidget {

  ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    //下划线widget预定义以供复用。
    var height = 0.0;
    MyListTitle(0, onChanged: (value) {
      print("回调hhh ${value.height}");
      height = value.height;

    }).build(context);

    return SizedBox(
        height: 200,
        child: ListView.builder(
          controller: _scrollController,
            itemCount: 100,
            itemExtent: 50, //强制高度为50.0
            itemBuilder: (BuildContext context, int index) {
              print("listviewitemBuilder${index}");

              // return MyListTitle(index, onChanged: (value) {
              return TextButton(child:Text("$index"),onPressed: (){
              print("自动加载 initState 完成回调");
              _scrollController.jumpTo(500);
              });
            }));
  }
}

class MyListTitle extends StatelessWidget {
  var index;
  final ValueChanged<Size> onChanged;
  var setWidgetSize;

  var globalKey = GlobalKey(debugLabel: "saf");

  MyListTitle(this.index, {required this.onChanged});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      print("自动加载 initState 完成回调");
      _afterLayout(context);
    });
    return TextButton(child:Text("$index", key: globalKey),onPressed: (){
      print("自动加载 initState 完成回调");
      onChanged(Size(0,0));
    },);
  }

  _afterLayout(BuildContext context) {
    _getSize(context);
    _getPosition();
  }

  _getPosition() {}

  _getSize(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    final height = size.height;
    print('Container widht MediaQuery is $width, height is $height');
    final containerWidth = context.size!.width;
    final containerHeight = context.size!.height;
    print('Container widht is $containerWidth, height is $containerHeight');
    onChanged(context.size!);
  }
}

class ListViewSeparated3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //下划线widget预定义以供复用。
    Widget divider1 = Divider(
      color: Colors.blue,
    );
    Widget divider2 = Divider(color: Colors.green);
    return SizedBox(
        height: 200,
        child: ListView.separated(
          itemCount: 100,

          //列表项构造器
          itemBuilder: (BuildContext context, int index) {
            return ListTile(title: Text("$index"));
          },
          //分割器构造器
          separatorBuilder: (BuildContext context, int index) {
            return index % 2 == 0 ? divider1 : divider2;
          },
        ));
  }
}
///错误
class _ListViewBuilder4 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {


    return Column(children: <Widget>[
      ListTile(title:Text("商品列表")),
      Expanded(
        child: ListView.builder(itemBuilder: (BuildContext context, int index) {
          return ListTile(title: Text("$index"));
        }),
      ),
    ]);
  }
}

///无限加载的控件
///
///
class InfiniteListView extends StatefulWidget {
  @override
  _InfiniteListViewState createState() => _InfiniteListViewState();
}

class _InfiniteListViewState extends State<InfiniteListView> {
  static const loadingTag = "##loading##"; //表尾标记
  var _words = <String>[loadingTag];

  @override
  void initState() {
    super.initState();
    //获取控件宽高
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      print("自动加载 initState 完成回调");
      _afterLayout();
    });
    print("自动加载 initState");
    _retrieveData();
  }

  _afterLayout() {
    _getSize();
    _getPosition();
  }

  _getPosition() {}

  _getSize() {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    final height = size.height;
    print('Container widht MediaQuery is $width, height is $height');
    final containerWidth = context.size!.width;
    final containerHeight = context.size!.height;
    print('Container widht is $containerWidth, height is $containerHeight');
  }

  @override
  Widget build(BuildContext context) {
    print("自动加载 build");
    return Scaffold(
      body: ListView.separated(
        itemCount: _words.length,
        itemBuilder: (context, index) {
          //如果到了表尾
          if (_words[index] == loadingTag) {
            //不足100条，继续获取数据
            if (_words.length - 1 < 100) {
              //获取数据
              _retrieveData();
              //加载时显示loading
              return Container(
                padding: const EdgeInsets.all(16.0),
                alignment: Alignment.center,
                child: SizedBox(
                  width: 24.0,
                  height: 24.0,
                  child: CircularProgressIndicator(strokeWidth: 2.0),
                ),
              );
            } else {
              //已经加载了100条数据，不再获取数据。
              return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(16.0),
                child: Text(
                  "没有更多了",
                  style: TextStyle(color: Colors.grey),
                ),
              );
            }
          }
          //显示单词列表项
          return ListTile(
            title: Text(_words[index]),
            onTap: () {
              print("自动加载点击事件$index");
            },
          );
        },
        separatorBuilder: (context, index) => Divider(height: .0),
      ),
    );
  }

  void _retrieveData() {
    Future.delayed(Duration(seconds: 2)).then((e) {
      setState(() {
        //重新构建列表
        _words.insertAll(
          _words.length - 1,
          //每次生成20个单词
          generateWordPairs().take(20).map((e) => e.asPascalCase).toList(),
        );
      });
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("自动加载 didChangeDependencies");
  }

  @override
  void didUpdateWidget(covariant InfiniteListView oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    print("自动加载 didUpdateWidget");
  }

  @override
  void deactivate() {
    super.deactivate();
    print("自动加载 deactive");
  }

  @override
  void dispose() {
    super.dispose();
    print("自动加载 dispose");
  }

  @override
  void reassemble() {
    super.reassemble();
    print("自动加载 reassemble");
  }
}
